// textarea
const editor = document.getElementById('editor');
// 拖拽文件提示窗
const dragHint = document.getElementById('dragHint');
// 切换主题开关
const themeToggle = document.querySelector('.theme-switch input');
// 字数统计
const wordCount = document.getElementById('wordCount');
// 替换弹窗
const replacePopup = document.getElementById('replacePopup');
// 查找-字符
const findText = document.getElementById('findText');
// 替换-字符
const replaceText = document.getElementById('replaceText');
	
// 初始化函数
function init() {
    loadContentAndFontSize();
    initTheme();
    setupEventListeners();
}

// 初始化文本内容
function loadContentAndFontSize() {
    chrome.storage.local.get(["content", "fontSize"]).then((result) => {
        editor.value = result.content || '　　';
        editor.style.fontSize = `${result.fontSize || 30}px`;
        requestAnimationFrame(() => {
            editor.scrollTop = editor.scrollHeight;
            editor.focus();
            updateWordCount();
        });
    }).catch((error) => {
        console.error('初始化失败:', error);
        editor.value = '初始化错误，请刷新页面';
    });
}

// 初始化主题
function initTheme() {
    const darkMediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
    toggleDarkMode(!darkMediaQuery.matches);
    // 监听系统主题变化
    darkMediaQuery.addEventListener('change', (e) => toggleDarkMode(!e.matches));
}

// 切换主题颜色
function toggleDarkMode(isDark) {
    document.body.classList.toggle('dark-mode', !isDark);
    themeToggle.checked = isDark;
}

// 下载文件
function saveFile() {
    const fileName = prompt("请输入文件名", Date.now());
    if (fileName) {
        const blob = new Blob([editor.value], { type: 'text/plain' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = fileName + '.txt';
        a.click();
    }
}
	
// 调整字体大小
function adjustFontSize(change) {
    const newSize = Math.max(12, parseInt(getComputedStyle(editor).fontSize) + change);
    editor.style.fontSize = `${newSize}px`;
    clearTimeout(this.fontSizeTimer);
    this.fontSizeTimer = setTimeout(() => {
        editor.scrollTop = editor.scrollHeight;
        editor.focus();
    }, 500);
}

// 重置
function reset() {
    if (confirm('确定要清空所有内容吗？')) {
        editor.value = '　　';
        editor.focus();
        chrome.storage.local.clear();
        editor.style.fontSize = '30px';
        wordCount.textContent = '字数: 0';
    }
}

// 读取text文件内容
function readTextFile(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = function(event) {
            resolve(event.target.result);
        };
        reader.onerror = reject;
        reader.readAsText(file);
    });
}

// 文件读取
function readFile(file) {
    readTextFile(file).then(text => {
        editor.value = text;
        editor.focus();
        editor.dispatchEvent(new Event("input", { bubbles: true }));
    }).catch(error => {
        console.error('读取文件时出错:', error);
    });
}

// 文件预览
function previewFile(file) {
    readTextFile(file).then(text => {
        const htmlContent = `
            <!DOCTYPE html>
            <html lang="zh-CN">
            <head>
                <meta charset="UTF-8">
                <title>${file.name}</title>
                <style>pre{font-size: 22px;white-space: pre-wrap;overflow-wrap: break-word;max-width: 100%;}</style>
            </head>
            <body>
                <pre>${text}</pre>
            </body>
            </html>
        `;
        chrome.tabs.create({
            url: `data:text/html;charset=utf-8,${encodeURIComponent(htmlContent)}`
        });
    }).catch(error => {
        console.error('预览文件时出错:', error);
    });
}

// 查找下一个
function findNext() {
    const find = findText.value;
    if (find) {
        const start = editor.selectionEnd;
        const text = editor.value;
        const index = text.indexOf(find, start);
        if (index !== -1) {
            selectText(index, index + find.length);
        } else {
            const newIndex = text.indexOf(find);
            if (newIndex !== -1) {
                selectText(newIndex, newIndex + find.length);
            } else {
                alert('未找到匹配文本');
            }
        }
    }
}

// 替换单个
function replaceSingle() {
    const find = findText.value;
    const replace = replaceText.value;
    if (find) {
        const start = editor.selectionStart;
        const end = editor.selectionEnd;
        const text = editor.value;
        if (text.slice(start, end) === find) {
            replaceAndFindNext(text, start, end, replace);
        } else {
            const firstIndex = text.indexOf(find);
            if (firstIndex !== -1) {
                replaceAndFindNext(text, firstIndex, firstIndex + find.length, replace);
            } else {
                alert('未找到匹配文本');
            }
        }
    }
}

// 替换并查找下一个
function replaceAndFindNext(text, start, end, replace) {
    const newText = text.slice(0, start) + replace + text.slice(end);
    editor.value = newText;
    editor.dispatchEvent(new Event("input", { bubbles: true }));
    const nextIndex = newText.indexOf(findText.value, start + replace.length);
    if (nextIndex !== -1) {
        selectText(nextIndex, nextIndex + findText.value.length);
    } else {
        const firstIndex = newText.indexOf(findText.value);
        if (firstIndex !== -1) {
            selectText(firstIndex, firstIndex + findText.value.length);
        }
    }
}
// 全部替换
function replaceAll() {
    const find = findText.value;
    const replace = replaceText.value;
    if (find) {
        editor.value = editor.value.replace(new RegExp(find, 'g'), replace);
        editor.dispatchEvent(new Event("input", { bubbles: true }));
    } else {
        alert('请输入要查找的文本');
	}
}
// 选择文本
function selectText(start, end) {
    editor.setSelectionRange(start, end);
    editor.focus();
    scrollToSelection();
}

// 调整滚动位置以显示选中的文本
function scrollToSelection() {
    const selectionStart = editor.selectionStart;
    const lineHeight = parseInt(getComputedStyle(editor).lineHeight);
    const linesBeforeSelection = (editor.value.slice(0, selectionStart).match(/\n/g) || []).length;
    const scrollTop = linesBeforeSelection * lineHeight;
    editor.scrollTop = scrollTop;
}

// 处理回车键
function handleEnterKey(e) {
    if (e.key === 'Enter') {
        e.preventDefault();
        const startPos = editor.selectionStart;
        const endPos = editor.selectionEnd;
        const value = editor.value;
        const newValue = value.substring(0, startPos) + '\n　　' + value.substring(endPos);
        editor.value = newValue;
        const newCursorPos = startPos + 3;
        editor.setSelectionRange(newCursorPos, newCursorPos);
    }
}

// 处理输入文字
function handleInput() {
    clearTimeout(this.handleInputTimer);
    this.handleInputTimer = setTimeout(() => {
        chrome.storage.local.set({ content: editor.value });
        updateWordCount();
    }, 500);
}

// 字数统计方法
function updateWordCount() {
    wordCount.textContent = `字数: ${editor.value.replace(/\s+/g, '').length}`;
}

// 处理拖拽文件
function handleDragOver(e) {
    e.preventDefault();
    dragHint.style.display = 'block';
}

function handleDragLeave() {
    dragHint.style.display = 'none';
}

function handleDrop(e) {
    e.preventDefault();
    dragHint.style.display = 'none';
    const file = e.dataTransfer.files[0];
    if (file && file.type === 'text/plain') {
        readFile(file);
    }
}

// 处理读取文件输入变化
function handleFileInputChange(e) {
    const file = e.target.files[0];
    if (file && file.type === 'text/plain') {
        readFile(file);
    }
}

// 处理预览文件输入变化
function handlePreviewInputChange(e) {
    const files = e.target.files;
    for (let i = 0; i < files.length; i++) {
        const file = files[i];
        if (file && file.type === 'text/plain') {
            previewFile(file);
        }
    }
}

// 处理快捷键
function handleKeyDown(e) {
    if (e.ctrlKey && e.key === 'q') {
		// 隐藏/显示按钮区
        const topDiv = document.getElementById('topDiv');
		const isHidden = topDiv.style.visibility === 'hidden';
		topDiv.style.visibility = isHidden ? 'visible' : 'hidden';
		document.getElementById('containerLeft').style.display = isHidden ? 'block' : 'none';
    } else if (e.ctrlKey && e.key.toLowerCase() === 's') {
        e.preventDefault();
        saveFile();
    } else if (e.ctrlKey && e.key === 'r') {
        e.preventDefault();
		// 隐藏/显示替换弹窗
		const isHidden = replacePopup.style.display === 'none';
		replacePopup.style.display = isHidden ? 'block' : 'none';
    }
}

// 定义定时器变量
let increaseInterval;
let decreaseInterval;

// 设置事件监听器
function setupEventListeners() {
    // 监听 textarea
    editor.addEventListener('keydown', handleEnterKey);
    editor.addEventListener('input', handleInput);
    editor.addEventListener('dragover', handleDragOver);
    editor.addEventListener('dragleave', handleDragLeave);
    editor.addEventListener('drop', handleDrop);

    // 监听按钮
	// 读取文件
	const fileInput = document.getElementById('fileInput');
    document.getElementById('openFile').addEventListener('click', () => fileInput.click());
    fileInput.addEventListener('change', handleFileInputChange);
	// 预览文件
    const previewInput = document.getElementById('previewInput');
	document.getElementById('openMultipleFiles').addEventListener('click', () => previewInput.click());
    previewInput.addEventListener('change', handlePreviewInputChange);
    document.getElementById('saveFile').addEventListener('click', saveFile);
    // 增加字体大小
	const increaseButton = document.getElementById('increaseFontSize');
	increaseButton.addEventListener('click', () => adjustFontSize(2));
	increaseButton.addEventListener('mousedown', () => {
        increaseInterval = setInterval(() => adjustFontSize(2), 100);
    });
    increaseButton.addEventListener('mouseup', () => {
        clearInterval(increaseInterval);
    });
    increaseButton.addEventListener('mouseout', () => {
        clearInterval(increaseInterval);
    });
	// 减小字体大小
	const decreaseButton = document.getElementById('reduceFontSize');
	decreaseButton.addEventListener('click', () => adjustFontSize(-2));
	decreaseButton.addEventListener('mousedown', () => {
        decreaseInterval = setInterval(() => adjustFontSize(-2), 100);
    });
    decreaseButton.addEventListener('mouseup', () => {
        clearInterval(decreaseInterval);
    });
    decreaseButton.addEventListener('mouseout', () => {
        clearInterval(decreaseInterval);
    });

    document.getElementById('reset').addEventListener('click', reset);
    themeToggle.addEventListener('change', (e) => toggleDarkMode(e.target.checked));
    document.getElementById('findNext').addEventListener('click', findNext);
    document.getElementById('replaceSingle').addEventListener('click', replaceSingle);
    document.getElementById('replaceAll').addEventListener('click', replaceAll);
    document.getElementById('closePopup').addEventListener('click', () => replacePopup.style.display = 'none');

    // 监听快捷键
    document.addEventListener('keydown', handleKeyDown);
}

// 页面关闭
window.onbeforeunload = (e) => {
    chrome.storage.local.set({ fontSize: parseInt(getComputedStyle(editor).fontSize) });
    // e.returnValue = '您有未保存的内容';
    // return e.returnValue;
};

// 初始化应用
document.addEventListener('DOMContentLoaded', init);